package com.funsport.controller.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.funsport.common.Result;
import com.funsport.entity.Role;
import com.funsport.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色管理控制器
 */
@RestController
@RequestMapping("/web/role")
public class WebRoleController {
    
    @Autowired
    private RoleService roleService;
    
    /**
     * 分页查询角色列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int pageSize,
            @RequestParam(required = false) String keyword
    ) {
        Page<Role> rolePage = roleService.getPage(page, pageSize, keyword);
        
        Map<String, Object> data = new HashMap<>();
        data.put("items", rolePage.getRecords());
        data.put("total", rolePage.getTotal());
        data.put("page", rolePage.getCurrent());
        data.put("pageSize", rolePage.getSize());
        
        return Result.success(data);
    }
    
    /**
     * 获取所有角色（不分页）
     */
    @GetMapping("/all")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<List<Role>> all() {
        return Result.success(roleService.getAllRoles());
    }
    
    /**
     * 获取角色详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<Role> getById(@PathVariable Long id) {
        Role role = roleService.getById(id);
        if (role == null) {
            return Result.error("角色不存在");
        }
        return Result.success(role);
    }
    
    /**
     * 创建角色
     */
    @PostMapping
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<Role> create(@RequestBody Role role) {
        // 检查编码是否已存在
        Role existing = roleService.getByCode(role.getCode());
        if (existing != null) {
            return Result.error("角色编码已存在");
        }
        
        role.setStatus("active");
        Role created = roleService.create(role);
        return Result.success(created);
    }
    
    /**
     * 更新角色
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<Role> update(@PathVariable Long id, @RequestBody Role role) {
        Role existing = roleService.getById(id);
        if (existing == null) {
            return Result.error("角色不存在");
        }
        
        role.setId(id);
        Role updated = roleService.update(role);
        return Result.success(updated);
    }
    
    /**
     * 删除角色
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<Void> delete(@PathVariable Long id) {
        // 检查是否为系统预设角色
        Role role = roleService.getById(id);
        if (role != null && 
            ("SUPER_ADMIN".equals(role.getCode()) || 
             "ADMIN".equals(role.getCode()) || 
             "USER".equals(role.getCode()))) {
            return Result.error("不能删除系统预设角色");
        }
        
        roleService.delete(id);
        return Result.success();
    }
    
    /**
     * 获取角色的权限ID列表
     */
    @GetMapping("/{id}/permissions")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<List<Long>> getRolePermissions(@PathVariable Long id) {
        List<Long> permissionIds = roleService.getRolePermissionIds(id);
        return Result.success(permissionIds);
    }
    
    /**
     * 分配权限给角色
     */
    @PostMapping("/{id}/permissions")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<Void> assignPermissions(
            @PathVariable Long id,
            @RequestBody Map<String, List<Long>> request
    ) {
        List<Long> permissionIds = request.get("permissionIds");
        roleService.assignPermissions(id, permissionIds);
        return Result.success();
    }
}

